package com.qingfeng.client;

import com.alibaba.fastjson.JSONObject;
import com.qingfeng.client.bean.Buyer;
import com.qingfeng.client.bean.Seller;
import com.qingfeng.client.service.BuyerService;
import com.qingfeng.client.service.RedisService;
import com.qingfeng.exception.LsException;
import com.qingfeng.mjwt.LoginToken;
import com.qingfeng.mjwt.PassToken;
import com.qingfeng.util.CodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 *
 * 登录拦截器
 * @author zhangyuefei
 * @version 1.0
 * @date 2020/3/5 3:08 下午
 */
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {


    @Autowired
    private BuyerService buyerService;

    @Autowired
    private RedisService redisService;

    @Value("${server.servlet.context-path}")
    private String contextPath="";


    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().startsWith(contextPath+"/codeLogin")
                || request.getRequestURI().startsWith(contextPath+"/wxpay/notify")
                || request.getRequestURI().startsWith(contextPath+"/newLogin")
                || request.getRequestURI().startsWith(contextPath+"/swagger_ui.html")){
            return true;
        }


        Buyer user = (Buyer) request.getSession().getAttribute("buyerBean");
        if (user == null) {
            //未登录,返回登录页面
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", CodeEnum.UNAUTHORIZED.getCode());
                jsonObject.put("message","用户未登录");
                out.append(jsonObject.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
            return false;
        }else {
            //放行
            return true;
        }
    }


//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
//
//        String token = request.getHeader("token");
////        如果不是映射到方法，直接通过
//        if (!(object instanceof HandlerMethod)){
//            return true;
//        }
//
//        HandlerMethod handlerMethod = (HandlerMethod) object;
//        Method method = handlerMethod.getMethod();
////        检查是否有passtoken注释，如果有则跳过
//        if (method.isAnnotationPresent(PassToken.class)){
//            PassToken passToken = method.getAnnotation(PassToken.class);
//            if (passToken.required()){
//                return true;
//            }
//        }
////        检查是否有用户权限注解
//        if (method.isAnnotationPresent(LoginToken.class)){
//            LoginToken loginToken = method.getAnnotation(LoginToken.class);
//            if (loginToken.required()){
//                //执行token认证
//                if (token==null){
//                    throw new LsException(CodeEnum.ERROR,"无token请重新登录");
//                }
//                //获取token中的userId
//                Buyer buyer = (Buyer) redisService.getToken(token);
//                if (buyer==null){
//                    throw new LsException(CodeEnum.AUTHENTICATEERROR,"用户不存在请重新登录");
//                }
//                redisService.updateTokenTime(token);
//            }
//        }
//        return true;
//    }



    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
